﻿package lucene.file 
{
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	
	import lucene.LuceneError;
	
	/**
	 * ...
	 * @author FreakDev
	 */
	public class FileHandler extends FileStream
	{
		
		private var _file:File;
		
		public function FileHandler(file:File = null, mode:String = FileMode.READ) 
		{
			super();
			
			if (null != file) {
				this._file = file;
				try {
					this.open(this._file, mode);
				}
				catch (e:Error) {
					throw new LuceneError(e.message)
				}
			}
		}
		
		public function readUInt32():int
		{
			return this.readUnsignedInt();
		}
		
		public function readUInt64():Number
		{
			var high:int = this.readUInt32();
			var low:int	 = this.readUInt32();
			
			return (high << 4) | low;
		}
		
		public function readVInt():Number
		{
			var i:int = this.readByte();
			var value:Number = i & 127;
			for (var shift:int=7; (i & 128) != 0; shift += 7) {
				i = this.readByte();
				value |= (i & 127) << shift;
			}
			return value;
		}
		
		public function readString():String
		{
			var len:Number = this.readVInt();
			return this.readUTFBytes(len);
		}
		
		public function length():Number
		{
			return this._file.size;
		}
		
		public function seek(offset:Number, cur:Boolean = false):void
		{
			if (!cur) {
				this.position = offset;
			}
			else {
				this.position = this.position + offset;
			}
		}
		
	}
	
}